#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>
#include <cassert>
#include <unistd.h>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <ctype.h>
#include"Log.hpp"


class Sock
{
private:
    const static int gbacklog = 20;
public:
    Sock(){}
    int Socket()
    {
        int listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (listensock < 0) 
        {   
            logMessage(FATAL, "creat sock error! %d : %s", errno, strerror(errno));
            exit(-1);
        }
        logMessage(NORMAL, "creat sock success! %d", listensock);
        return listensock;
    }

    void Bind(int sock, uint16_t port, std::string ip = "0.0.0.0")
    {
        sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &local.sin_addr);
        if(bind(sock, (struct sockaddr*)&local, sizeof local) < 0)
        {
            logMessage(FATAL, "bind error! %d : %s", errno, strerror(errno));
            exit(-2);
        }
        logMessage(NORMAL, "bind success! %d", sock);

    }

    void Listen(int sock)
    {
        if(listen(sock, gbacklog) < 0)
        {
            logMessage(FATAL, "listen error! %d : %s", errno, strerror(errno));
            exit(-3);
        }
        logMessage(NORMAL, "listen success! %d", sock);
    }

    //服务端
    int Accept(int sock, std::string* clientip, uint16_t* clientport)
    {
        struct sockaddr_in local;
        //memset(&local, 0, sizeof local);
        socklen_t len = sizeof local;
        int serversock = accept(sock, (struct sockaddr*)&local, &len);
        if( serversock < 0)
        {
            logMessage(ERROR, "accept error! %d : %s", errno, strerror(errno));
            return -1;
        }
        if(clientip) *clientip = inet_ntoa(local.sin_addr);
        if(clientport) *clientport = ntohs(local.sin_port);

        logMessage(NORMAL, "listen success! %d", sock);
        return serversock;
    }

    //客户端
    bool Connect(int sock, const std::string &server_ip, const uint16_t &server_port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(server_port);
        server.sin_addr.s_addr = inet_addr(server_ip.c_str());

        if(connect(sock, (struct sockaddr*)&server, sizeof(server)) == 0) return true;
        else return false;
    }
};